import { createWebHashHistory, createRouter } from "vue-router";
// 路由组件导入
import main from '../components/layout/MainLayout.vue'
import Login from '../../../../../IDEA/ideaProject/quickcar_vue/quick-car_-system_-vue/src/components/Login.vue'
import UserRegister from "@/view/user/userRegister.vue";
import GoodsList from "@/view/user/goodsList.vue";
import AdminLayout from "@/components/layout/AdminLayout.vue";
import AdminLogin from "../../../../../IDEA/ideaProject/quickcar_vue/quick-car_-system_-vue/src/components/AdminLogin.vue";
import UserList from "@/view/admin/UserList.vue";
import AdminList from "@/view/admin/AdminList.vue";
import AddProduct from "@/view/admin/AddProduct.vue";
import Product from "@/view/admin/Product.vue";
import GoodsDetail from "@/view/user/GoodsDetail.vue"
import Cart from "@/view/user/Cart.vue";
import SelectGoodsList from "@/view/user/SelectGoodsList.vue";
import Order from "@/view/user/Order.vue";
import OrderManagement from "@/view/admin/OrderManagement.vue";
import OrderItems from "@/view/user/OrderItems.vue";
import OrderListEcharts from "@/view/OrderListEcharts.vue";
import {useTokenStore} from "@/stores/tokenStore.js";
// 定义路由元信息，标记需要登录和角色权限的路由
const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    // 公开路由（无需登录）
    {
        path: '/login',
        component: Login,
        meta: { public: true }
    },
    {
        path: '/register',
        component: UserRegister,
        meta: { public: true }
    },
    {
        path: '/adminLogin',
        component: AdminLogin,
        meta: { public: true }
    },
    // 用户端受保护路由
    {
        path: '/main',
        component: main,
        meta: { requiresAuth: true, role: 'user' },
        children: [
            { path: 'goodsList', component: GoodsList }  //子路由路径不能加 /
        ]
    },
    // 管理端受保护路由
    {
        path: '/adminLayout',
        component: AdminLayout,
        meta: { requiresAuth: true, role: 'admin' },
        redirect: '/adminLayout/userList', // 新增：默认跳转到管理员的第一个子路由（userList）
        children: [
            { path: 'userList', component: UserList },
            { path: 'adminList', component: AdminList },
            { path: 'addProduct', component: AddProduct},
            { path: 'product', component: Product },
            { path: 'orderManagement', component: OrderManagement },
            { path: 'orderListEcharts', component: OrderListEcharts}
        ]
    },
    // 其他用户端受保护路由
    {
        path: '/goods-detail',
        name: 'GoodsDetail',
        component: GoodsDetail,
        meta: { requiresAuth: true, role: 'user' }
    },
    {
        path: '/cart',
        name: 'Cart',
        component: Cart,
        meta: { requiresAuth: true, role: 'user' }
    },
    {
        path: '/selectGoodsList',
        component: SelectGoodsList,
        meta: { requiresAuth: true, role: 'user' }
    },
    {
        path: '/order',
        component: Order,
        meta: { requiresAuth: true, role: 'user' }
    },
    {
        path: '/orderItems',
        component: OrderItems,
        meta: { requiresAuth: true, role: 'user' }
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes: routes
})

// 路由守卫实现
router.beforeEach((to, from, next) => {
    const authStore = useTokenStore()
    const isLoggedIn = authStore.isLoggedIn()

// 1. 处理公开路由
    if (to.meta.public) {
        // 已登录用户访问登录页时，只拦截“与自身角色匹配的登录页”
        if (isLoggedIn) {
            // 场景1：已登录管理员访问“管理员登录页（/adminLogin）”→ 拦截跳转
            if (authStore.isAdmin() && to.path === '/adminLogin') {
                next('/adminLayout/userList');
                return;
            }
            // 场景2：已登录普通用户访问“普通登录页（/login）”→ 拦截跳转
            if (authStore.isUser() && to.path === '/login') {
                next('/main/goodsList');
                return;
            }
            // 场景3：已登录用户访问“其他公开路由”（如 /register、/adminRegister 或跨角色登录页）→ 不拦截，允许进入
            next();
            return;
        }
        // 未登录状态：访问任何公开路由（包括 /adminLogin）→ 正常显示
        next();
        return;
    }
    // 2. 处理需要登录的路由
    if (to.meta.requiresAuth) {
        // 未登录状态
        if (!isLoggedIn) {
            if (to.meta.role === 'admin') {
                next('/adminLogin')
            } else {
                next('/login')
            }
            return
        }

        // 3. 验证角色权限
        if (to.meta.role && to.meta.role !== authStore.role) {
            if (authStore.isAdmin()&& to.path !== '/adminLayout/userList') {
                next('/adminLayout/userList')
            } else if(authStore.isUser()&& to.path !== '/main/goodsList'){
                next('/main/goodsList')
            }else{
                next(false)
            }
            return
        }
    }

    // 所有验证通过
    next()
})
export default router